<?php

namespace App\Services\Applet\Payment;

use App\Exceptions\PaymentException;
use App\Exceptions\SponsorException;
use App\Helpers\MvcHelper;
use App\Models\Applet\Order\ShopMasterOrderModel;
use App\Models\Applet\Order\ShopOrderModel;
use App\Models\Applet\Order\SponsorMasterOrderModel;
use App\Models\Applet\Order\SponsorOrderModel;
use Exception;
use Illuminate\Support\Facades\DB;

class PaymentService extends BasePaymentService
{
    /**
     * 获取支付参数
     * @param array $params
     * @return array
     * @throws PaymentException
     * @throws SponsorException
     * @throws Exception
     */
    public function payParams(array $params): array
    {
        // 查询订单
        $orderInfo = $this->getOrderService($params['orderType'])->getOrderInfo($params['orderNo']);
        if ($orderInfo['user_id'] != MvcHelper::getLoginUserId()) {
            throw new PaymentException('不是自己的订单', PaymentException::CODE_1002);
        }

        if ($orderInfo['order_price'] > 0) {
            return $this->_payParams($params, $orderInfo);
        } else {
            return $this->_zeroPay($params, $orderInfo);
        }
    }

    /**
     * @param array $params
     * @param array $orderInfo
     * @return array
     * @throws Exception
     */
    public function _zeroPay(array $params, array $orderInfo): array
    {
        // 更新订单状态
        switch ($params['orderType']) {
            case 10:
                $this->_zeroPaySponsor($params, $orderInfo);
                break;
            case 20:
                $this->_zeroPayShop($params, $orderInfo);
                break;
        }

        return [
            'type' => 10,
        ];
    }

    /**
     * 认养订单零元购
     * @param array $params
     * @param array $orderMasterInfo
     * @return void
     * @throws Exception
     */
    public function _zeroPaySponsor(array $params, array $orderMasterInfo)
    {
        // 查询子订单
        $orderInfo = $this->getSponsorOrderModel()->getItemByOrderMasterId($orderMasterInfo['id'], [
            'id', 'goods_id', 'quantity'
        ]);

        $orderInfoGoods = $this->getSponsorOrderGoodsModel()->getItemByOrderIdAndGoodsId($orderInfo['id'], $orderInfo['goods_id'], [
            'id', 'province_id', 'city_id', 'region_id', 'name', 'price', 'cover_img', 'cycle', 'start_time'
        ]);

        DB::transaction(function () use ($params, $orderInfo, $orderMasterInfo, $orderInfoGoods) {
            // 更新主订单
            $this->getSponsorMasterOrderModel()->updateItemById($orderMasterInfo['id'], [
                'order_status' => SponsorMasterOrderModel::ORDER_STATUS_COMPLETED,
                'pay_type' => SponsorMasterOrderModel::PAY_TYPE_INTEGRAL,
                'pay_status' => SponsorMasterOrderModel::PAY_STATUS_SUCCESS,
                'pay_time' => date("Y-m-d H:i:s", time()),
            ]);
            // 更新子订单
            $this->getSponsorOrderModel()->updateItemById($orderInfo['id'], [
                'order_status' => SponsorOrderModel::ORDER_STATUS_COMPLETED,
            ]);
            // 创建认养记录
            $this->getUserSponsorModel()->addItem([
                'user_id' => $orderMasterInfo['user_id'],
                'goods_id' => $orderInfo['goods_id'],
                'order_id' => $orderInfo['id'],
                'province_id' => $orderInfoGoods['province_id'],
                'city_id' => $orderInfoGoods['city_id'],
                'region_id' => $orderInfoGoods['region_id'],
                'name' => $orderInfoGoods['name'],
                'price' => $orderInfoGoods['price'],
                'cover_img' => $orderInfoGoods['cover_img'],
                'cycle' => $orderInfoGoods['cycle'],
                'start_time' => $orderInfoGoods['start_time'],
                'quantity' => $orderInfo['quantity'],
            ]);
        });
    }

    /**
     * 商城订单零元购
     * @param array $params
     * @param array $orderMasterInfo
     * @return void
     * @throws Exception
     */
    public function _zeroPayShop(array $params, array $orderMasterInfo)
    {
        // 查询子订单
        $orderInfo = $this->getShopOrderModel()->getItemByOrderMasterId($orderMasterInfo['id']);

        DB::transaction(function () use ($params, $orderInfo, $orderMasterInfo) {
            // 更新主订单
            $this->getShopMasterOrderModel()->updateItemById($orderMasterInfo['id'], [
                'order_status' => ShopMasterOrderModel::ORDER_STATUS_SUCCESS,
                'pay_type' => ShopMasterOrderModel::PAY_TYPE_INTEGRAL,
                'pay_status' => ShopMasterOrderModel::PAY_STATUS_SUCCESS,
                'pay_time' => date("Y-m-d H:i:s", time()),
            ]);
            // 更新子订单
            $this->getShopOrderModel()->updateItemById($orderInfo['id'], [
                'order_status' => ShopOrderModel::ORDER_STATUS_SUCCESS,
            ]);
        });
    }


    /**
     * @throws PaymentException
     * @throws Exception
     */
    public function _payParams(array $params, array $orderInfo): array
    {
        // 查询用户信息
        $userInfo = $this->getUserModel()->getItemById(MvcHelper::getLoginUserId(), ['id', 'openid']);

        // 获取支付参数
        $payParams = $this->getPaymentParams(
            $orderInfo['order_no'],
            $orderInfo['order_price'],
            $params['payType'],
            $params['platform'],
            $params['orderType'],
            [
                'params' => [
                    'orderType' => $params['orderType'],
                ],
                'openid' => $userInfo['openid'],
            ]);

        $createPaymentOrder = [
            'order_type' => $params['orderType'],
            'order_id' => $orderInfo['id'],
            'transaction_id' => $payParams['prepayid'],
            'pay_type' => $params['payType'],
            'price' => $orderInfo['order_price'],
        ];

        // 创建支付订单
        $this->getPaymentOrderModel()->addItem($createPaymentOrder);

        $payParams['type'] = 20;
        return $payParams;
    }
}
